//
//  CCCityModel.m
//  Party
//
//  Created by its on 15/3/17.
//  Copyright (c) 2015年 coco. All rights reserved.
//

#import "CCCityModel.h"
#import "CCLoctionService.h"
#import <LinqToObjectiveC/NSArray+LinqExtensions.h>
#import <LinqToObjectiveC/NSDictionary+LinqExtensions.h>

@interface CCCityModel()
@property(nonatomic, strong) CCLoctionService *service;
@property(nonatomic, strong) NSDictionary *cityDic;
@property(nonatomic, strong) NSArray *cityKeyArr;
@end

@implementation CCCityModel

- (id) init {
  if (self = [super init]) {
    _searchSignal = [[RACSubject subject] setNameWithFormat:@"CCCityModel searchSignal"];
    [self setupSearchSignal];
  }
  return self;
}

- (void) setupSearchSignal {
  _findAllSignal =  [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
    NSString *hotFile = [[NSBundle mainBundle] pathForResource:@"hotdic" ofType:@"plist"];
    NSString *allFile = [[NSBundle mainBundle] pathForResource:@"citydict" ofType:@"plist"];
    NSDictionary *hotDic = [NSDictionary dictionaryWithContentsOfFile:hotFile];
    NSDictionary *allDic = [NSDictionary dictionaryWithContentsOfFile:allFile];
    NSArray *allcityKey = [allDic allKeys];
    
    self.service = [[CCLoctionService alloc] init];
    [_service getCity:^(NSString *city) {
      NSArray *array = @[@"?",@"@"];
      array = [array linq_where:^BOOL(id item) {
        if ([item isEqualToString:@"?"] && city == nil)
          return NO;
        return YES;
      }];
      NSArray *keyArr = [array linq_concat:allcityKey ];
      NSDictionary *resultDic = [allDic linq_Merge:hotDic];
      if (city) {
        resultDic = [resultDic linq_Merge:@{@"?":@[city]}];
      }
      RACTuple *tuple = [RACTuple tupleWithObjects:[keyArr linq_sort],resultDic, nil];
      self.cityDic = resultDic;
      self.cityKeyArr = [keyArr linq_sort];
      [subscriber sendNext: tuple];
      if (city == nil) {
        [subscriber sendError:[NSError errorWithDomain:@"定位失败，请在设置中允许本程序访问位置服务" code:101 userInfo:nil]];
      }
    }];
    RACDisposable *dispose = [RACDisposable disposableWithBlock:^{
    }];
    return dispose;
  }];
  
}

- (void) searchWithString:(NSString *)str {
  NSLog(@"search str:%@",str);
  NSDictionary *searchResultDic = [self.cityDic linq_where:^BOOL(id key, NSArray * value) {
    value = [value linq_where:^BOOL(NSString* item) {
      if ([item containsString: str]) return YES;
      return NO;
    }];
    if (value.count > 0) {
      return YES;
    } else {
      return NO;
    }
  }];
  [_searchSignal sendNext: searchResultDic];
}

- (void) searchWithNil {
  [_searchSignal sendNext: self.cityDic];
}
@end
